<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8" />
  <title>菜单管理</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="../../layuimini/lib/layui-v2.5.5/css/layui.css" media="all" />
  <link rel="stylesheet" href="../../layuimini/css/public.css" media="all" />
  <link rel="stylesheet" href="../../layuimini/lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all" />
  <style>
    .all_resource_class {
      font-size: 18;
      color: grey;
      font-weight: bold;
      padding-left: 20px;
    }

    .resource_tree_class {
      padding-left: 20px;
      margin-top: 20px;
    }

    .add_menu_1 {
      padding-left: 20px;
    }

    .hidden {
      display: none;
    }
  </style>
</head>

<body>
  <div class="layuimini-container">
    <div class="layuimini-main">
      <fieldset class="layui-elem-field layui-field-title">
        <legend>全部菜单列表</legend>
      </fieldset>

      <div class="add_menu_1">
        <button type="button" class="layui-btn layui-btn-normal layui-btn-sm" id="add_btn">
          <i class="layui-icon layui-icon-add-1"></i>新增一级菜单
        </button>
      </div>
      <!-- 树形菜单列表 -->
      <div class="resource_tree_class" id="resourceTree"></div>
    </div>
  </div>

  <script></script>

  <script src="../../layuimini/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
  <script src="../../layuimini/js/lay-config.js" charset="utf-8"></script>

  <!-- 菜单新增编辑弹框 -->
  <script type="text/html" id="menuEditDialog">
      <form
        id="menuEditForm"
        lay-filter="menuEditForm"
        class="layui-form"
        style="padding-left:20px;margin-top: 20px;padding-right: 20px;"
      >
        <div class="layui-form layuimini-form">
          <input name="id" type="hidden" />
          <div class="layui-form-item" style="display: none;">
            <label class="layui-form-label">上级菜单ID:</label>
            <div class="layui-input-block">
              <input name="parentId" class="layui-input" />
            </div>
          </div>
          <div class="layui-form-item" id="parent_item">
            <label class="layui-form-label required ">上级菜单:</label>
            <div class="layui-input-inline">
              <input
                type="text"
                name="parentName"
                class="layui-input"
                disabled
              />
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label required">菜单名称:</label>
            <div class="layui-input-inline">
              <input
                name="title"
                placeholder="请输入菜单名称"
                class="layui-input"
                lay-verify="required"
                lay-verType="tips"
              />
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">跳转地址:</label>
            <div class="layui-input-inline">
              <input
                name="href"
                placeholder="请输入菜单地址"
                class="layui-input"
              />
            </div>
          </div>

          <div class="layui-form-item" id="menu_sort">
            <label class="layui-form-label required">菜单排序:</label>
            <div class="layui-input-inline">
              <input
                type="number"
                name="sort"
                lay-affix="number"
                placeholder="菜单排序"
                value="0"
                class="layui-input"
                min="0"
                lay-verify="required"
                lay-verType="tips"
              />
            </div>
          </div>

          <div class="layui-form-item">
            <label class="layui-form-label">菜单图标:</label>
            <div class="layui-input-inline">
              <input
                name="icon"
                type="text"
                id="iconPicker"
                lay-filter="iconPicker"
                class="hide"
              />
            </div>
          </div>

          <div class="layui-form-item hidden">
            <label class="layui-form-label"></label>
            <button
              id="submit_btn"
              class="layui-btn layui-btn-normal"
              lay-filter="menuEditSubmit"
              lay-submit
            >
              提交
            </button>
            <button
              class="layui-btn layui-btn-primary"
              type="button"
              ew-event="closeDialog"
              id="Cancel"
            >
              取消
            </button>
          </div>
        </div>
      </form>
    </script>

  <script type="text/javascript">
    layui.use(
      ["layer", "form", "common", "miniTab", "tree", "iconPickerFa"],
      function (args) {
        var layer = layui.layer,
          common = layui.common,
          form = layui.form,
          miniTab = layui.miniTab,
          tree = layui.tree,
          iconPickerFa = layui.iconPickerFa,
          $ = layui.jquery;

        // 渲染
        tree.render({
          elem: "#resourceTree",
          data: getData(),
          edit: ["add", "update", "del"],
          showLine: true,
          onlyIconControl: false, // 是否仅允许节点左侧图标控制展开收缩
          customOperate: true, // 开启源码自定义增删改查
          click: function (obj) {
            // layer.msg(JSON.stringify(obj.data));
          },

          operate: function (obj) {
            var type = obj.type; // 得到操作类型：add、edit、del
            var data = obj.data; // 得到当前节点的数据
            var elem = obj.elem; // 得到当前节点元素

            var id = data.id; //
            if (type === "add") {
              // 增加节点
              showEditModel(data, undefined);
              // 非一级菜单隐藏排序
              $("#menu_sort").addClass("hidden");
            } else if (type === "update") {
              showEditModel(undefined, data);
              if (!data.parentName) {
                // 一级资源 隐藏"父级菜单"
                $("#parent_item").addClass("hidden");
              } else {
                // 非一级资源 隐藏“菜单排序”
                $("#menu_sort").addClass("hidden");
              }
            } else if (type === "del") {
              // 删除节点
              if (data && data.children && data.children.length > 0) {
                layer.msg('存在子菜单，不允许删除', { icon: 2 });
                return;
              }
              confirmDel(data);
            }
          },
        });

        // 删除
        function confirmDel(val) {
          layer.confirm(
            "确定要删除节点【" + val.title + "】？",
            {
              skin: "layui-layer-admin",
              shade: 0.1,
            },
            function (i) {
              common.ajax(
                common.api + "/menu/" + val.id + "/delete",
                {},
                function (res) {
                  if (res.code === 200) {
                    layer.msg(res.msg, { icon: 1 });
                    // 删除成功刷新页面
                    // 刷新当前页面
                    setTimeout("window.location.reload()", 500);
                  } else {
                    layer.close(index);
                    layer.msg(res.msg, { icon: 2, time: 2000 });
                  }
                },
                "DELETE",
                function (data) {
                  console.log(data);
                  layer.msg(data.msg, { icon: 2, time: 1000 });
                  return;
                }
              );
              layer.close(i);
            }
          );
        }
        // 渲染图标选择器
        function initIconPickerFa() {
          iconPickerFa.render({
            // 选择器，推荐使用input
            elem: "#iconPicker",
            // fa 图标接口
            url: "/layuimini/lib/font-awesome-4.7.0/less/variables.less",
            // 是否开启搜索：true/false，默认true
            search: true,
            // 是否开启分页：true/false，默认true
            page: true,
            // 每页显示数量，默认12
            limit: 12,
            // 点击回调
            click: function (data) {
              console.log(data);
            },
            // 渲染成功后的回调
            success: function (d) {
              console.log(d);
            },
          });
        }

        function showEditModel(data, formData) {
          var idx = layer.open({
            type: 1,
            area: ["460px", "350px"],
            title: formData ? "编辑" : "添加",
            anim: 1,
            shade: 0.6,
            content: $("#menuEditDialog").html(),
            btn: ["提交", "取消"],
            btnAlign: "r", // 按钮对其方式，'l','c','r'
            btn1: function (index, layero, that) {
              // 提交
              $("#submit_btn").click();
            },
            // 取消
            btn2: function (index, layero, that) {
              return true;
            },

            success: function (layero, dIndex) {
              // 设置图标默认
              iconPickerFa.checkIcon("iconPicker", "");
              // 渲染图标选择器
              initIconPickerFa();
              // 如果是新增
              if (data) {
                // 回显父组件id
                form.val("menuEditForm", {
                  parentId: data.id,
                  parentName: data.title,
                });
              }
              // 如果是修改
              // 回显表单数据
              if (formData) {
                form.val("menuEditForm", formData);
                if (formData.icon) {
                  // 如果菜单有icon，回显到菜单选择器
                  var arr = formData.icon.split(" ");
                  if (arr && arr.length == 2) {
                    iconPickerFa.checkIcon("iconPicker", arr[1]);
                  }
                }
              }
              // 表单提交事件
              form.on("submit(menuEditSubmit)", function (data) {
                if (data.field.icon) {
                  // 如果菜单有图标，把菜单格式和init.json的菜单名称格式保持一致
                  data.field.icon = "fa " + data.field.icon;
                }
                common.ajax(
                  formData
                    ? common.api + "/menu/update"
                    : common.api + "/menu/add",
                  JSON.stringify(data.field),
                  function (res) {
                    if (res.code === 200) {
                      layer.close(dIndex);
                      layer.msg(res.msg, { icon: 1 });
                      // 刷新当前页面
                      setTimeout("window.location.reload()", 500);
                    } else {
                      layer.msg(res.msg, { icon: 2 });
                    }
                  },
                  formData ? "put" : "post",
                  function (data) {
                    layer.close(loadIndex);
                    layer.msg(data.msg, { icon: 2 });
                  }
                );
                return false;
              });

              $("#Cancel").click(function () {
                layer.close(idx);
              });
            },
          });
        }

        function getData() {
          var data = [];
          $.ajax({
            url: common.api + "/menu/allMenu", //后台数据请求地址
            type: "get",
            async: false,
            headers: { authorization: common.getToken("token") },
            success: function (result) {
              // 设置节点默认展开
              if (result && result.length > 0) {
                for (let k = 0; k < result.length; k++) {
                  const e = result[k];
                  e.spread = true;
                  data.push(e);
                }
              }
            },
          });

          console.log(data);
          return data;
        }

        // 新增一级菜单
        $(document).on("click", "#add_btn", function () {
          showEditModel(undefined, undefined);
          // 一级菜单 隐藏父菜单输入框
          $("#parent_item").addClass("hidden");
        });
      }
    );
  </script>
</body>

</html>